package com.springboot.application.controller;

import com.springboot.application.entity.UserEntity;
import com.springboot.application.service.UserService;
import org.json.JSONObject;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author zhengzihong
 * @version 1.0.0
 * @date 2018/11/1
 * @Description
 */
@RestController
public class UserController {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RedisTemplate redisTemplate;


    @Resource
    private UserService userService;

    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    public String getUserInfo(HttpServletRequest request) {
        String id = request.getParameter("id");
        if (StringUtils.isEmpty(id)) {
            return "入参为空";
        }
        UserEntity userEntity = userService.getUserInfoById(Long.valueOf(id));
        if (userEntity != null) {
            JSONObject jsonObject = new JSONObject(userEntity);
            return jsonObject.toString();
        }
        return "根据id:" + id + "获取不到用户信息";
    }


    @RequestMapping(value = "/getUserInfoList", method = RequestMethod.GET)
    public String getUserInfoList() {
        List<UserEntity> list = userService.findAll();
        if (!CollectionUtils.isEmpty(list)) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("list", list);
            return jsonObject.toString();
        }
        return "获取不到用户信息";
    }


    @RequestMapping(value = "/getRedisValue", method = RequestMethod.GET)
    public String getRedisValue(HttpServletRequest request) {
        String key = request.getParameter("key");
        if (StringUtils.isEmpty(key)) {
            return "入参为空";
        }
        Object o = redisTemplate.opsForValue().get(key);
        if (o == null) {
            return "值为空";
        }
        return (String) o;
    }


    @RequestMapping(value = "/setRedisValue", method = RequestMethod.GET)
    public void setRedisValue(HttpServletRequest request) {
        String key = request.getParameter("key");
        String value = request.getParameter("value");
        if (StringUtils.isEmpty(key)) {
            return;
        }
        System.out.println("aaa");
        redisTemplate.opsForValue().set(key, value);
    }


}
